package cn.ljy.uem.service.impl;

import cn.ljy.authority.config.security.TokenConfig;
import cn.ljy.authority.dao.mapper.SysDepartmentMapper;
import cn.ljy.authority.dao.mapper.SysRoleMapper;
import cn.ljy.authority.dao.mapper.SysUserMapper;
import cn.ljy.authority.dao.mapper.SysUserRoleMapper;
import cn.ljy.authority.model.SysDepartment;
import cn.ljy.authority.model.SysUser;
import cn.ljy.authority.service.SysUserService;
import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.exception.model.MyWebException;
import cn.ljy.common.utils.password.SHA;
import cn.ljy.common.utils.redis.StringRedisUtils;
import cn.ljy.uem.config.token.SchoolTokenConfig;
import cn.ljy.uem.dao.*;
import cn.ljy.uem.model.*;
import cn.ljy.uem.model.query.SchoolClassQuery;
import cn.ljy.uem.model.query.SchoolMajorQuery;
import cn.ljy.uem.model.query.SchoolStudentQuery;
import cn.ljy.uem.service.SchoolStudentService;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class ISchoolStudentService extends IBaseService<SchoolStudent, SchoolStudentQuery> implements SchoolStudentService {

    @Autowired
    private SchoolStudentMapper mapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SchoolClassMapper schoolClassMapper;
    @Autowired
    private SchoolTokenConfig schoolTokenConfig;
    @Autowired
    private TokenConfig tokenConfig;
    @Autowired
    private StringRedisUtils stringRedisUtils;
    @Autowired
    private SchoolMajorMapper schoolMajorMapper;
    @Autowired
    private SchoolCourseMapper schoolCourseMapper;
    @Autowired
    private SchoolGradeMapper schoolGradeMapper;
    @Autowired
    private SchoolDepartmentMapper schoolDepartmentMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysDepartmentMapper sysDepartmentMapper;

    @Autowired
    private SysUserService sysUserService;

    @Override
    protected void beforeGet(Serializable id) {

    }

    @Override
    protected void beforeUpdate(SchoolStudent schoolStudent) {
//        log.info(String.valueOf(schoolStudent));
        if (schoolStudent.getId() != null && schoolStudent.getUserId()==null) {               //如果传输进来的学生信息里面没有账户ID 而数据库有 查找存入
            schoolStudent.setUserId(mapper.findById(schoolStudent.getId()).getUserId());
        }
        if (schoolStudent.getStudentNumber() != null || schoolStudent.getClassId()!=null) {
            //查找学生的部门  班级>专业>部门
            //查找部门属于那个系统部门
            SysDepartment sysDepartment = new SysDepartment();
            Long sysDepartmentId = mapper.findSysDepartmentIdByClassId(schoolStudent.getClassId());
            sysDepartment = sysDepartmentMapper.findById(sysDepartmentId);
            //新增user账户,将教师的信息保存到user表里
            SysUser sysUser = new SysUser();
            sysUser.setId(schoolStudent.getUserId());
            sysUser.setDepartment(sysDepartment);
            sysUser.setUsername("S"+schoolStudent.getStudentNumber());
            sysUser.setPassword(SHA.getResult("123456"));
            sysUser.setNickName(schoolStudent.getName());
            sysUser.setSex(schoolStudent.getSex());
            sysUser.setStatus(1);
            sysUser.setDescription(schoolStudent.getDescription());
            sysUserMapper.update(sysUser);                                                  //如果学生表学号或者班级修改更新用户表的部门及账号

        }
    }

    @Override
    protected void afterUpdate(SchoolStudent schoolStudent) {

    }

    @Override
    protected void beforeSave(SchoolStudent schoolStudent) {
        //添加之前的验证
        if (schoolStudent == null) {
            throw new MyWebException("请确认传入对象是否为空");
        } else {
//            System.out.println("不为空提示");
            if (schoolStudent.getName() == null) {
                throw new MyWebException("学生姓名为空,请输入学生姓名");
            } else if (schoolStudent.getSex() == null) {
                throw new MyWebException("学生性别为空,请输入学生性别");
            } else if (!StringUtils.hasLength(schoolStudent.getStudentNumber())) {
                throw new MyWebException("学生学号为空,请输入学生学号");
            }else if (schoolStudent.getClassId() == null) {
                throw new MyWebException("学生班级为空,请输入学生班级");
            } else {
                if (mapper.countByStudentNumberAndNotId(schoolStudent.getStudentNumber(),schoolStudent.getId()) > 0) {
                    throw new MyWebException("学号" + schoolStudent.getStudentNumber() + "的学生已存在");
                } else {
                    //查找学生的部门  班级>专业>部门

                    //查找部门属于那个系统部门
                    SysDepartment sysDepartment = new SysDepartment();
                    Long sysDepartmentId = mapper.findSysDepartmentIdByClassId(schoolStudent.getClassId());
                    sysDepartment = sysDepartmentMapper.findById(sysDepartmentId);
                    //新增user账户,将教师的信息保存到user表里
                    if (sysUserMapper.findOneByUsername("S"+schoolStudent.getStudentNumber())!=null){
                        throw new MyWebException("该学生账户已存在");                                    //如果学生表 没有 该学生，但是账户表里 有 该学生账户，则抛出学生账户 已存在 异常
                    }
                    SysUser sysUser = new SysUser();
                    sysUser.setId(null);
                    sysUser.setDepartment(sysDepartment);
                    sysUser.setUsername("S"+schoolStudent.getStudentNumber());
                    sysUser.setPassword(SHA.getResult("123456"));
                    sysUser.setNickName(schoolStudent.getName());
                    sysUser.setSex(schoolStudent.getSex());
                    sysUser.setStatus(1);
                    sysUser.setDescription(schoolStudent.getDescription());
                    sysUserMapper.save(sysUser);
                    //添加学生
                    if (sysUser.getId() != null) {
                        schoolStudent.setUserId(sysUser.getId());
                    }
                    //为学生的账户（user表）添加学生角色（-12）
                    sysUserRoleMapper.save(sysUser.getId(),super.getStudentRoleId());
                }
            }
        }
    }


    @Override
    protected void afterSave(SchoolStudent schoolStudent) {

    }

    @Override
    public void delete(@NotEmpty(message = "操作失败：请选择要移除的记录") Serializable[] ids) {
//        new Serializable[0];

        //获取学生记录
        List<Serializable> userIds=mapper.findUserIdsByIds(ids);
        super.delete(ids);
        Serializable[] userIdArray=userIds.toArray(new Serializable[userIds.size()]);
        sysUserRoleMapper.deleteByUserIds(userIdArray);
        sysUserMapper.deleteByIdIn(userIdArray);

//
//        sysUserRoleMapper.deleteByUserIds(id);
//        sysUserMapper.deleteByIdIn(id);


    }

    @Override
    protected void beforeDelete(Serializable[] ids) {

//        Serializable[]  userIds = new Serializable[0];
//        //获取学生记录
//        for (Serializable id : ids) {
//
//            SchoolStudent schoolStudent = mapper.findById(id);
//            log.warn(String.valueOf(schoolStudent));
//            //取出学生对象上的userId
//                    userIds.add(schoolStudent.getUserId());
//        }
//
//        //删除学生记录
//        super.delete(ids);
////        Serializable[] userIds1 =
//        sysUserRoleMapper.deleteByUserIds(userIds);
//        sysUserMapper.deleteByIdIn(userIds);

    }


//    @Override
//    protected void beforeDelete(Serializable[] ids) {
//        //获取要删除的教师账户id集合
//        List<Long> userIds=new ArrayList<>();
//        for (Serializable id : ids) {
//            //取出教师对象上的userid
//            SchoolStudent schoolStudent = mapper.findById(id);
//            log.warn(String.valueOf(schoolStudent));
//            userIds.add(schoolStudent.getUserId());
////            if (schoolStudent == null) {
////                throw new MyWebException("该学生未找到,请输入正确的学生ID");
////            } else {
//            //创建删除的user表集合
//
////             {schoolStudent.getUserId()};
//
//            log.warn(String.valueOf(schoolStudent.getUserId()));
////                sysUserRoleMapper.deleteByUserIds(userId);
//            log.warn(String.valueOf(schoolStudent));
////            sysUserMapper.deleteByIdIn(userId);
////            }
//        }
////        for (Serializable id : ids) {
////            SchoolStudent schoolStudent = mapper.findById(id);
////            log.warn(String.valueOf(schoolStudent));
////            if (schoolStudent == null) {
////                throw new MyWebException("该学生未找到,请输入正确的学生ID");
////            }
////
////        }
////        sysUserRoleMapper.deleteByUserIds(ids);
//
//
//    }


    @Override
    protected void afterDelete(Serializable[] ids) {
//        log.warn(ids);
//        for (Serializable id : ids) {
//            log.warn(String.valueOf(id.toString()));
//            //取出教师对象上的userid
//            SchoolStudent schoolStudent = mapper.findById(id);
//            log.warn(String.valueOf(schoolStudent));
//            //创建删除的user表集合
//            Serializable[] userId = {schoolStudent.getUserId()};
//            log.warn(String.valueOf(schoolStudent.getUserId()));
////            sysUserMapper.deleteByIdIn(userId);
//            sysUserMapper.deleteByIdIn(userId);
//        }
    }



    @Override
    protected void beforeFindAll(SchoolStudentQuery query) {
        if(query!=null){
            //1.如果传递了班级id，则根据班级id查找学生范围
            if(query.getClassIds()!=null&&query.getClassIds().size()>0){
                //利用查询类查找
                List<Integer> classIds=new ArrayList<>();
//                for (Integer claId:classIds){
                //如果班级Id和年级ID不为空
                    if(query.getGradeId() != null){
                        SchoolGrade schoolGrade = schoolGradeMapper.findById(query.getGradeId());
                        //先根据年级id查找所有班级
                        SchoolClassQuery schoolClassQuery = new SchoolClassQuery();
                        schoolClassQuery.setGradeId(schoolGrade.getId());
//                        schoolClassQuery.setId(claId);
                        List<SchoolClass> schoolClassList = schoolClassMapper.findAll(schoolClassQuery);
                        System.out.println(schoolClassList);
                        //再从年级下的班级找出属于那几个班级的
                        for (SchoolClass schoolClass:schoolClassList){
                            for (Integer classID:query.getClassIds()){
                                if (schoolClass.getId() == classID){
                                    classIds.add(schoolClass.getId());
                                }
                            }
                        }
                        if (classIds==null || classIds.isEmpty()){
                            throw new MyWebException("该年级下没有班级");
                        }
                        query.setClassIds(classIds);
                    }else {
                        //反之如果年级ID为空那么就直接查找
                        query.setClassIds(query.getClassIds());
                    }
//                }
//                query.setClassIds(classIds);
                //2.如果没有传递班级id,但是传递了年级id，则根据年级id查询
            }else if(query.getGradeId()!=null){
               SchoolGrade schoolGrade= schoolGradeMapper.findById(query.getGradeId());
                //根据年级id查找所有班级
                SchoolClassQuery schoolClassQuery=new SchoolClassQuery();
                schoolClassQuery.setGradeId(schoolGrade.getId());
                List<SchoolClass> schoolClassList= schoolClassMapper.findAll(schoolClassQuery);

                //根据班级查找所有学生
                //班级id集合
                List<Integer> classIds=new ArrayList<>();
                for (SchoolClass schoolClass:schoolClassList){
                    classIds.add(schoolClass.getId());
                }
                //利用学生查询类查询
                query.setClassIds(classIds);
            } else if(query.getMajorIds()!=null&&query.getMajorIds().size()>0){//2.如果没有传递班级id，但是传递了专业id，则根据专业id对应的班级集合查找学生
                //利用班级查询类查找专业下的班级
                SchoolClassQuery schoolClassQuery=new SchoolClassQuery();
                schoolClassQuery.setMajorIds(query.getMajorIds());
                List<SchoolClass> schoolClasses=schoolClassMapper.findAll(schoolClassQuery);
                //存放通过专业id查找出来的班级列表
                List<Integer> classList =new ArrayList<>();
                for (SchoolClass schoolClass:schoolClasses){
                    classList.add(schoolClass.getId());
                }
                //将班级id存入学生查询类
                query.setClassIds(classList);
                //3.如果上述的班级id和专业id都没有传递，但是传递了系部id，则根据系部id对应的班级集合查找学生
            } else if (query.getDepartmentId()!=null) {
                //查找出系部下的所有专业
                //利用专业的查询类
                SchoolMajorQuery schoolMajorQuery=new SchoolMajorQuery();
                schoolMajorQuery.setDepartmentId(query.getDepartmentId());
                List<SchoolMajor> schoolMajorList= schoolMajorMapper.findAll(schoolMajorQuery);
                //专业id集合
                List<Integer> Majorids=new ArrayList<>();
                //将专业id加入查询类
                for (SchoolMajor schoolMajor:schoolMajorList){
                    Majorids.add(schoolMajor.getId());
                }
                //将集合中的专业id加入班级查询类 查找专业下的所有班级
                SchoolClassQuery schoolClassQuery=new SchoolClassQuery();
                schoolClassQuery.setMajorIds(Majorids);
                List<SchoolClass> schoolClassList=  schoolClassMapper.findAll(schoolClassQuery);
                //班级id集合
                List<Integer> ClassIds=new ArrayList<>();
                for (SchoolClass schoolClass:schoolClassList){
                    ClassIds.add(schoolClass.getId());
                }
                //利用学生查询类查询
                if (ClassIds==null || ClassIds.isEmpty()){
                    throw new MyWebException("该部门下没有班级");
                }
                query.setClassIds(ClassIds);
            }

            //4.如果班级、专业、院系都没有查询，则直接查询满足条件的所有班级学生（即sql语句不应该有class_id=x的条件）
        }
    }

    @Override
    protected void afterFindAll(List<SchoolStudent> list) {
        for(SchoolStudent schoolStudent:list){
            //添加班级关联属性
            if(schoolStudent.getClassId()!=null){
                //查找学生所属班级
                SchoolClass schoolClass=schoolClassMapper.findById(schoolStudent.getClassId());
                //赋值
                schoolStudent.setSchoolClass(schoolClass);
                if(schoolClass.getMajorId()!=null){
                    SchoolMajor schoolMajor = schoolMajorMapper.findById(schoolClass.getMajorId());
                    schoolStudent.setSchoolMajor(schoolMajor);
                    if(schoolMajor.getDepartmentId()!=null){
                        SchoolDepartment schoolDepartment = schoolDepartmentMapper.findById(schoolMajor.getDepartmentId());
                        schoolStudent.setSchoolDepartment(schoolDepartment);
                    }
                }
                if(schoolClass.getGradeId()!=null){
                    SchoolGrade schoolGrade = schoolGradeMapper.findById(schoolClass.getGradeId());
                    schoolStudent.setSchoolGrade(schoolGrade);
                }
            }
        }
    }

    @Override
    protected void afterGet(SchoolStudent schoolStudent) {
        //添加班级关联属性
        if(schoolStudent.getClassId()!=null){
            //查找学生所属班级
            SchoolClass schoolClass=schoolClassMapper.findById(schoolStudent.getClassId());
            //赋值
            schoolStudent.setSchoolClass(schoolClass);
            if(schoolClass.getMajorId()!=null){
                SchoolMajor schoolMajor = schoolMajorMapper.findById(schoolClass.getMajorId());
                schoolStudent.setSchoolMajor(schoolMajor);
                if(schoolMajor.getDepartmentId()!=null){
                    SchoolDepartment schoolDepartment = schoolDepartmentMapper.findById(schoolMajor.getDepartmentId());
                    schoolStudent.setSchoolDepartment(schoolDepartment);
                }
            }
            if(schoolClass.getGradeId()!=null){
                SchoolGrade schoolGrade = schoolGradeMapper.findById(schoolClass.getGradeId());
                schoolStudent.setSchoolGrade(schoolGrade);
            }
        }
    }

    @Override
    public List<SchoolCourse> getCoursesOfStudent(SchoolStudent schoolStudent) {
        List<SchoolCourse> list=new ArrayList<>();
        if(schoolStudent!=null){//如果当前用户存在
            //获取当前学生登录账户对应的的班级
            List<SchoolClass> classList = schoolClassMapper.getStudentAllClasses(schoolStudent.getClassId());
            if(CollectionUtils.isEmpty(classList)){
                throw new MyWebException("该学生并无班级");
            }
            if(!classList.isEmpty()){//如果当前用户至少有班级存在
                //查找学对应班级下所有的教学任务
                //再查找该班教学任务对应的课程
                for (SchoolClass schoolClass:classList){
                    List<SchoolCourse> courseList = mapper.getCourseByClassId(schoolClass.getId());
                    for (SchoolCourse courseCourse:courseList){//查找课程并对课程进行一个过滤处理 过滤掉已经弃用课程
                        if (!schoolCourseMapper.getExpireByCourseId(courseCourse.getId())
                                ||schoolCourseMapper.getExpireByCourseId(courseCourse.getId())==null){
                            list.add(courseCourse);
                        }
                    }
                    if(CollectionUtils.isEmpty(list)){
                        throw new MyWebException("该学生并无课程");
                    }
                }
            }else{
                throw new MyWebException("操作失败：该学生未添加班级！");
            }
        }
        //查找教师信息下对应的课程
        return list;
    }

    /*
   方法二：如果说不想使用afterFindAll等方法来配合实现整个查询需求，那么可以直接用下面的方法直接替换实现
   @Override
    public List<SchoolStudent> findAll(SchoolStudentQuery query) {
        List<SchoolStudent> all = super.findAll(query);
        for(SchoolStudent schoolStudent:all){
            //添加班级关联属性
            if(schoolStudent.getClassId()!=null){
                //查找学生所属班级
                SchoolClass schoolClass=schoolClassMapper.findById(schoolStudent.getClassId());
                //赋值
                schoolStudent.setSchoolClass(schoolClass);
            }
        }
        return all;
    }*/
}
